package com.penjin.android.message.company;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.penjin.android.R;
import com.penjin.android.constants.HttpConstants;
import com.penjin.android.domain.PenjinCompany;
import com.penjin.android.domain.PenjinStaff;
import com.penjin.android.domain.PenjinUser;
import com.penjin.android.http.HttpService;
import com.penjin.android.service.UserService;
import com.penjin.android.utils.HttpUtil;
import com.penjin.android.utils.ToastHelper;
import com.penjin.android.view.CustomProgressDialog;
import com.penjin.android.view.TitleBarView;

import org.apache.http.Header;
import org.json.JSONObject;

import cn.hugo.android.scanner.CaptureActivity;

/**
 * 绑定企业界面
 * Created by Administrator on 2016/3/11.
 */
public class BindCompanyActivity extends Activity implements View.OnClickListener {

    TitleBarView titleBarView;
    EditText bindCode;
    ImageView getBindCode;
    TextView ok;
    TextView cancle;
    TextView createCompany;

    HttpService httpService;
    TextHttpResponseHandler bindCompanyHandler;
    TextHttpResponseHandler getBindCodeHandler;
    RequestHandle getBindCodeHandle;
    RequestHandle bindCompanyHandle;

    CustomProgressDialog progressDialog;
    PenjinUser currentUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_activity_bind_company);
        initData(savedInstanceState);
        initView();
        initHttp();

    }

    private void initView() {
        progressDialog = CustomProgressDialog.createDialog(this);
        progressDialog.setMessage("请稍后...");
        titleBarView = (TitleBarView) findViewById(R.id.titleBarView);
        titleBarView.setTitleBarListener(new TitleBarView.TitleBarListener() {
            @Override
            public void left(View view) {
                BindCompanyActivity.this.finish();
            }

            @Override
            public void center(View view) {

            }

            @Override
            public void right(View view) {

            }
        });
        bindCode = (EditText) findViewById(R.id.bindCode);
        getBindCode = (ImageView) findViewById(R.id.getBindCode);
        ok = (TextView) findViewById(R.id.ok);
        cancle = (TextView) findViewById(R.id.cancel);
        createCompany = (TextView) findViewById(R.id.createCompany);

        getBindCode.setOnClickListener(this);
        ok.setOnClickListener(this);
        cancle.setOnClickListener(this);
        createCompany.setOnClickListener(this);
    }

    private void initData(Bundle savedInstance) {
        UserService userService = UserService.getInstance(this.getApplicationContext());
        currentUser = userService.getCurrentUser();
        if (currentUser == null) {
            ToastHelper.showNotLogin(this);
            finish();
        }
    }

    private void initHttp() {
        this.httpService = HttpService.getInstance(this.getApplicationContext());
        bindCompanyHandler = new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                progressDialog.dismiss();
                if (s != null) {
                    System.out.println(s);
                    ToastHelper.showMessage(s, BindCompanyActivity.this);
                }
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                progressDialog.dismiss();
                try {
                    JSONObject jo = new JSONObject(s);
                    boolean result = jo.optBoolean("result");
                    if (result) {
                        ToastHelper.showMessage(jo.optString("msg"), BindCompanyActivity.this);
                        JSONObject jCompany = jo.optJSONObject("company");
                        PenjinCompany company = new PenjinCompany();
                        company.setCompanyName(jCompany.optString("name"));
                        company.setTelephone(jCompany.optString("telephone"));
                        company.setEmail(jCompany.optString("email"));
                        company.setAddress(jCompany.optString("address"));
                        company.setUrl(jCompany.optString("url"));
                        company.setCompanyPersonNumber(jCompany.optString("companyPersonNumber"));
                        company.setCompanyId(jCompany.optString("companyId"));

                        JSONObject jStaff = jo.optJSONObject("staff");
                        PenjinStaff staff = new PenjinStaff();
                        staff.setStaffNumber(jStaff.optString("staffnumber"));
                        staff.setDepartment(jStaff.optString("department"));
                        staff.setInOffice(jStaff.optString("inoffice"));
                        staff.setPosition(jStaff.optString("position"));
                        currentUser.setCompanyId(company.getCompanyId());
                        UserService userService = UserService.getInstance(BindCompanyActivity.this.getApplicationContext());
                        userService.saveCompany(company);
                        userService.saveUser(currentUser);
                        userService.saveCurrentStaff(staff);
                        ToastHelper.showAlertMessage(getApplicationContext(), R.layout.layout_dialog_alert_msg, "绑定企业成功!");
                        finish();
                    } else {
                        ToastHelper.showMessage("绑定失败，请确认绑定码后重试", getApplicationContext());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        getBindCodeHandler = new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                progressDialog.dismiss();
                if (s != null) {
                    System.out.println(s);
                }
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                progressDialog.dismiss();
                Toast.makeText(BindCompanyActivity.this, s, Toast.LENGTH_SHORT).show();
                try {
                    JSONObject jo = new JSONObject(s);
                    boolean result = jo.optBoolean("result");
                    if (result) {
                        bindCode.setText(jo.optString("bindCode"));
                    } else {
                        ToastHelper.showMessage(jo.optString("msg"), BindCompanyActivity.this);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.getBindCode:
                /*if (HttpUtil.isNetworkAvailable(this)) {
                    progressDialog.show();
                    try {
                        RequestParams params = new RequestParams();
                        params.put("userName", currentUser.getPhone());
                        this.getBindCodeHandle = this.httpService.postRequestWithHandle(this, HttpConstants.HOST + HttpConstants.AppBindCode, params, getBindCodeHandler);
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastHelper.showConnectionError(this);
                        progressDialog.dismiss();
                    }
                } else {
                    ToastHelper.showNoNetwork(this);
                }*/
                Intent captureIntent = new Intent(this, CaptureActivity.class);
                startActivityForResult(captureIntent, 1);
                break;
            case R.id.ok:
                if (HttpUtil.isNetworkAvailable(this)) {
                    String bindCode = this.bindCode.getEditableText().toString();
                    if (bindCode == null || bindCode.equals("")) {
                        ToastHelper.showMessage("绑定码不能为空", this);
                    } else {
                        progressDialog.show();
                        RequestParams requestParams = new RequestParams();
                        requestParams.put("bindCode", bindCode);
                        requestParams.put("userName", currentUser.getPhone());
                        try {
                            this.bindCompanyHandle = this.httpService.postRequestWithHandle(this, HttpConstants.HOST + HttpConstants.AppBind, requestParams, bindCompanyHandler);
                        } catch (Exception e) {
                            e.printStackTrace();
                            ToastHelper.showConnectionError(this);
                            progressDialog.dismiss();
                        }
                    }
                } else {
                    ToastHelper.showNoNetwork(this);
                }
                break;
            case R.id.cancel:
                this.finish();
                break;
            case R.id.createCompany:
                Intent intent = new Intent();
                intent.setClass(this, CreateCompanyActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (this.bindCompanyHandle != null) {
            bindCompanyHandle.cancel(true);
        }
        if (this.getBindCodeHandle != null) {
            getBindCodeHandle.cancel(true);
        }
        super.onDestroy();
    }
}
